﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPITest.Models;
using WebAPITest.Models.Database;

namespace WebAPITest.service
{
    public class UserService: IUserService
    {
        private readonly WebEnterpriseIIContext _db;
        /// <summary>
        /// 用户服务
        /// </summary>
        /// <param name="db"></param>
        public UserService(WebEnterpriseIIContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 根据用户名获取用户对象
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public User GetUserByUserName(string userName)
        {
            return _db.Users.FirstOrDefault(x => x.UserName == userName);
        }
        //服务层方法   接口
        //1、传入数据  1、前端传入数据
        //2、处理数据  2、接口处理数据
        //3、返回结果  3、返回结果给前端
        /// <summary>
        /// 获取用户名
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public bool ExixtUserByUserName(string userName)
        {
            return _db.Users.Any(x=>x.UserName==userName);

        }
        /// <summary>
        /// 添加一个新用户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public int AddNewUser(RegRequest request)
        {
            var user = new User()
            {
                UserName = request.UserName,
                Email = request.Email,
                NickName = request.NickName,
                Password = request.Password,
                CreateTime = DateTime.Now,
                Salt = 0,
                UserLevel = 1

            };
            _db.Users.Add(user);
            var row = _db.SaveChanges();
            return row;
        }
    }
}
